package com.liusr.template.config;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liusr
 * @date 2023/2/26
 * @package com.liusr.template.config
 * @Description: FastJsonConfig
 */
@Configuration
public class SpringMvcConfigure implements WebMvcConfigurer {

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		//创建fastjson消息转换器
		FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

		//创建配置类
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
		//修改配置返回内容的过滤
		//WriteNullListAsEmpty  ：List字段如果为null,输出为[],而非null
		//WriteNullStringAsEmpty ： 字符类型字段如果为null,输出为"",而非null
		//ReferenceDetection ：消除对同一对象循环引用的问题，默认为false（如果不配置有可能会进入死循环）
		//WriteNullBooleanAsFalse：Boolean字段如果为null,输出为false,而非null
		//WriteMapNullValue：是否输出值为null的字段,默认为false
		fastJsonConfig.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue
		, JSONWriter.Feature.WriteNullListAsEmpty
		, JSONWriter.Feature.WriteNullStringAsEmpty
		, JSONWriter.Feature.ReferenceDetection
		, JSONWriter.Feature.WriteNullBooleanAsFalse);
		List<MediaType> supportedMediaTypes = new ArrayList<>();
		supportedMediaTypes.add(MediaType.APPLICATION_JSON);
		fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
		fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
		//将fastjson添加到视图消息转换器列表内
		converters.add(0,fastJsonHttpMessageConverter);
	}
}
